package com.itobase.questionnaire.util;

import com.itobase.questionnaire.model.auth.User;
import com.itobase.questionnaire.template.Constant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;



import java.util.Optional;

/**
 * @author liucong
 * @date 2018/7/26
 */
public class AuthUtil {


    public static Optional<User> getUser() throws Throwable {
        Subject subject = SecurityUtils.getSubject();
        return Optional.of(Optional.ofNullable((User) subject.getPrincipal()).orElseThrow(() -> new RuntimeException("请先登录")));
    }

    public static String getUsername() throws Throwable {
        return getUser().map(User::getUsername).orElseThrow(() -> new RuntimeException("请先登录"));
    }

    public static String getUserId() throws Throwable {
        return getUser().map(User::getId).orElseThrow(() -> new RuntimeException("请先登录"));
    }

    public static void anonymousLogin() {
        Subject subject = SecurityUtils.getSubject();
        String username = "anonymous";
        String password = "anonymous";
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        System.out.println("匿名账号配置>>>>>>>>>>>>>>>>>>>>>>>>");
        subject.login(token);
    }

    public static Boolean isTeacher() throws Throwable {
        User user = getUser().orElseThrow(()->new RuntimeException("请先登录"));
        if(user.getUserTypeId().equals(Constant.TEACID)){
            return true;
        }else if(user.getUserTypeId().equals(Constant.STUID) || user.getUserTypeId().equals(Constant.GRADUATE_STUDENT_ID)){
            return false;
        }
        return false;
    }

}
